<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Java复习笔记, 博客">
    <meta name="description" content="个人学习储备知识与经验的秘密基地">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->

<script async src="https://www.googletagmanager.com/gtag/js?id=G-KDXT8Y4CLW"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }

    gtag('js', new Date());
    gtag('config', 'G-KDXT8Y4CLW');
</script>


    <title>Java复习笔记 | 不二博客</title>
    <link rel="icon" type="image/png" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/favicon.png">

    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/css/matery.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/css/my.css">

    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 6.3.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="不二博客" type="application/atom+xml">
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">不二博客</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">不二博客</div>
        <div class="logo-desc">
            
            个人学习储备知识与经验的秘密基地
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/weiyouwozuiku" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/weiyouwozuiku" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    
<script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/PageImg/程序设计/java.png')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Java复习笔记</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Java/">
                                <span class="chip bg-color">Java</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/" class="post-category">
                                程序设计
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-10-28
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2022-10-31
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    8.5k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    31 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/prism/prism.css">
        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="JVM">JVM<a class="anchor" href="#JVM">¶</a></h2>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_%E7%BC%96%E8%AF%91%E6%B5%81%E7%A8%8B.png" alt="Java复习笔记_编译流程.png"></p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_JVM.png" alt="Java复习笔记_JVM.png"></p>
<ul>
<li>Class Loader：依据特定格式，加载class文件到内存。</li>
<li>Execution Engine：对命令进行解析。</li>
<li>Native Interface：融合不同开发语言的原生库为Java所用。</li>
<li>Runtime Data Area：JVM内存空间结构模型。</li>
</ul>
<h3 id="ClassLoader">ClassLoader<a class="anchor" href="#ClassLoader">¶</a></h3>
<p>ClassLoader在Java中具有非常重要的作用，它主要工作在Class装载的加载阶段，其主要作用是从系统外部获取Class二进制数据流。它是Java的核心组件，所有Class都由ClassLoader进行加载，ClassLoader负责通过将Class文件中的二进制数据流装载进系统，然后交给Java虚拟机进行连接、初始化等操作。</p>
<h4 id="BootStrapClassLoader">BootStrapClassLoader<a class="anchor" href="#BootStrapClassLoader">¶</a></h4>
<p>C++编写，加载核心库java.*</p>
<h4 id="ExtClassLoader">ExtClassLoader<a class="anchor" href="#ExtClassLoader">¶</a></h4>
<p>Java编写，加载扩展库javax.*</p>
<h4 id="AppClassLoader">AppClassLoader<a class="anchor" href="#AppClassLoader">¶</a></h4>
<p>Java编写，加载程序所在目录</p>
<h4 id="自定义ClassLoader">自定义ClassLoader<a class="anchor" href="#自定义ClassLoader">¶</a></h4>
<p>Java编写，关键函数如下：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">protected</span> <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">&gt;</span></span> <span class="token function">findClass</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ClassNotFoundException</span><span class="token punctuation">{</span> 
    <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">ClassNotFoundException</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span> 
<span class="token punctuation">}</span>
<span class="token keyword">protected</span> <span class="token keyword">final</span> <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">&gt;</span></span> <span class="token function">defineClass</span><span class="token punctuation">(</span><span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> b<span class="token punctuation">,</span><span class="token keyword">int</span> off<span class="token punctuation">,</span><span class="token keyword">int</span> len<span class="token punctuation">)</span><span class="token keyword">throws</span> <span class="token class-name">ClassFormatError</span><span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token function">defineClass</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span>b<span class="token punctuation">,</span>off<span class="token punctuation">,</span>len<span class="token punctuation">,</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>例子：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//MyClassLoader.java</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span><span class="token class-name">ByteArrayOutputStream</span></span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span><span class="token class-name">File</span></span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span><span class="token class-name">FileInputStream</span></span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span><span class="token class-name">InputStream</span></span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyClassLoader</span> <span class="token keyword">extends</span> <span class="token class-name">ClassLoader</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> path<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> classLoaderName<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token class-name">MyClassLoader</span><span class="token punctuation">(</span><span class="token class-name">String</span> path<span class="token punctuation">,</span> <span class="token class-name">String</span> classLoaderName<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>path <span class="token operator">=</span> path<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>classLoaderName <span class="token operator">=</span> classLoaderName<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">//用于寻找类文件</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token class-name">Class</span> <span class="token function">findClass</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> b <span class="token operator">=</span> <span class="token function">loadClassData</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token function">defineClass</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> b<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> b<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">//用于加载类文件</span>
    <span class="token keyword">private</span> <span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token function">loadClassData</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        name <span class="token operator">=</span> path <span class="token operator">+</span> name <span class="token operator">+</span> <span class="token string">".class"</span><span class="token punctuation">;</span>
        <span class="token class-name">InputStream</span> in <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token class-name">ByteArrayOutputStream</span> out <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            in <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FileInputStream</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">File</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            out <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ByteArrayOutputStream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
            <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>i <span class="token operator">=</span> in<span class="token punctuation">.</span><span class="token function">read</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                out<span class="token punctuation">.</span><span class="token function">write</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
            <span class="token keyword">try</span> <span class="token punctuation">{</span>
                out<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                in<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> out<span class="token punctuation">.</span><span class="token function">toByteArray</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token comment">//ClassLoaderChecker.java</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ClassLoaderChecker</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ClassNotFoundException</span><span class="token punctuation">,</span> <span class="token class-name">IllegalAccessException</span><span class="token punctuation">,</span> <span class="token class-name">InstantiationException</span> <span class="token punctuation">{</span>
        <span class="token class-name">MyClassLoader</span> m <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MyClassLoader</span><span class="token punctuation">(</span><span class="token string">"/Users/baidu/Desktop/"</span><span class="token punctuation">,</span> <span class="token string">"myClassLoader"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Class</span> c <span class="token operator">=</span> m<span class="token punctuation">.</span><span class="token function">loadClass</span><span class="token punctuation">(</span><span class="token string">"Wali"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getParent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getParent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getParent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getParent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getParent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getParent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        c<span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="双亲委派机制">双亲委派机制<a class="anchor" href="#双亲委派机制">¶</a></h4>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE.png" alt="Java复习笔记_双亲委派.png"></p>
<p>采用双亲委派机制可以避免多份同样的字节码的加载。</p>
<h3 id="类的加载方式">类的加载方式<a class="anchor" href="#类的加载方式">¶</a></h3>
<ul>
<li>隐式加载：new</li>
<li>显式加载：loadClass，forName等</li>
</ul>
<h4 id="loadClass和forName的区别">loadClass和forName的区别<a class="anchor" href="#loadClass和forName的区别">¶</a></h4>
<p>类的加载过程</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_%E7%B1%BB%E7%9A%84%E8%A3%85%E8%BD%BD%E8%BF%87%E7%A8%8B.png" alt="Java复习笔记_类的装载过程.png "></p>
<ul>
<li>Class.forName的带的class是已经完成初始化的。如果项目中需要引入Mysql driver就需要使用forName以便执行其中的static块，完成初始化。</li>
<li>Class.loadClass得到的class时候还没有链接的。利用这个特性spring可以实现延迟加载，加快加载速度。</li>
</ul>
<h3 id="JVM内存模型">JVM内存模型<a class="anchor" href="#JVM内存模型">¶</a></h3>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_JVM%E5%86%85%E5%AD%98%E6%A8%A1%E5%9E%8B.png" alt="Java复习笔记_JVM内存模型.png "></p>
<ul>
<li>线程私有：程序计数器、虚拟机栈、本地方法栈</li>
<li>线程共享：MetaSpace、Java堆</li>
</ul>
<h4 id="程序计数器">程序计数器<a class="anchor" href="#程序计数器">¶</a></h4>
<ul>
<li>当前线程所执行的字节码号指示器（逻辑，而非物理）</li>
<li>和线程是一对一的关系及“线程私有”</li>
<li>改变计数器的值来选取下一条需要执行的字节码指令</li>
<li>对Java方法计数，如果是native方法则计数器值为Undefined</li>
<li>不会发生内存泄漏</li>
</ul>
<h4 id="虚拟机栈">虚拟机栈<a class="anchor" href="#虚拟机栈">¶</a></h4>
<ul>
<li>Java方法执行的内存模型</li>
<li>包含多个栈帧</li>
</ul>
<h5 id="栈帧">栈帧<a class="anchor" href="#栈帧">¶</a></h5>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_%E8%99%9A%E6%8B%9F%E6%9C%BA%E6%A0%88%E5%B8%A7.png" alt="Java复习笔记_虚拟机栈帧.png"></p>
<h6 id="局部变量表和操作数栈">局部变量表和操作数栈<a class="anchor" href="#局部变量表和操作数栈">¶</a></h6>
<p>局部变量表：包含方法执行过程中的所有变量</p>
<p>操作数栈：入栈、出栈、复制、交换、产生消费变量</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_add%E6%89%A7%E8%A1%8C.png" alt="Java复习笔记_add执行.png"></p>
<p>递归会引发java.lang.StackOverflowError异常就是因为递归过深，栈帧数超过虚拟机栈深度。</p>
<h4 id="本地方法栈">本地方法栈<a class="anchor" href="#本地方法栈">¶</a></h4>
<p>与虚拟机栈相似，主要作用于标注了native的方法。</p>
<h4 id="元空间与永久代">元空间与永久代<a class="anchor" href="#元空间与永久代">¶</a></h4>
<p>元空间（MateSpace）与永久代（PermGen）是都是用来存储Class信息，都是方法区的实现，只是实现方法不同。<strong>JDK1.8之后用元空间取代了永久代，元空间使用本地内存，而永久代使用的是jvm内存。</strong></p>
<p>MetaSpace相比PermGen的优势</p>
<ul>
<li>字符串常量池存在永久代中，容易出现性能问题和内存溢出</li>
<li>类和方法的信息大小难以确定，给永久代的大小指定带来了困难</li>
<li>永久代会为GC带来不必要的复杂性</li>
<li>方便HotSpot与其他JVM如Jrockit的集成</li>
</ul>
<h4 id="Java堆">Java堆<a class="anchor" href="#Java堆">¶</a></h4>
<ul>
<li>对象实例的分配区域</li>
<li>GC管理的主要区域</li>
</ul>
<h4 id="内存模型中堆和栈的区别">内存模型中堆和栈的区别<a class="anchor" href="#内存模型中堆和栈的区别">¶</a></h4>
<p>此处涉及到内存分配策略。</p>
<ul>
<li>静态存储：编译时确定每个数据目标在运行时的存储空间需求。要求代码中不能有可变数据结构也不允许有嵌套和递归的出现。</li>
<li>栈式存储：数据区需求在编译时未知，运行时模块入口前确定。</li>
<li>堆式存储：编译时或运行时模块入口都无法确定，动态分配。</li>
</ul>
<p>联系：引用对象、数组时，栈里定义变量保存堆中目标的首地址。如下图。</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_%E5%BC%95%E7%94%A8%E5%A0%86%E5%AF%B9%E8%B1%A1.png" alt="Java复习笔记_引用堆对象.png"></p>
<p>区别：</p>
<ul>
<li>管理方式：栈自动释放，编译器就能管理，堆需要GC。</li>
<li>空间大小：栈比堆小。</li>
<li>碎片相关：栈产生的碎片远小于堆。</li>
<li>分配方式：栈支持静态和动态分配，不需要考虑内存回收问题。而堆仅支持动态分配，即使有GC还是要考虑垃圾回收释放的问题。</li>
<li>效率：栈的效率比堆高。</li>
</ul>
<h3 id="JVM三大调参优化参数">JVM三大调参优化参数<a class="anchor" href="#JVM三大调参优化参数">¶</a></h3>
<ul>
<li>-Xss：规定了每个线程虚拟机栈（堆栈）的大小，一般256k,影响并发线程数的大小</li>
<li>-Xms：堆的初始值</li>
<li>-Xmx：堆能达到的最大值</li>
</ul>
<p>一般将Xms和Xmx设置成一样，因为当堆不够用而发生扩容时，会发生内存抖动，影响程序运行时的稳定性。</p>
<h2 id="反射">反射<a class="anchor" href="#反射">¶</a></h2>
<p>在运行状态中，对于任意一个类。都能够知道这个类的所有属性和方法；对于任意一个对象。都能够调用它的任意方法和属性；这种动态获取信息以及调用对象方法的功能称为java的反射机制。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//robot.java</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Robot</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> name<span class="token punctuation">;</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">sayHi</span><span class="token punctuation">(</span><span class="token class-name">String</span> helloSentence<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>helloSentence <span class="token operator">+</span> <span class="token string">" "</span> <span class="token operator">+</span> name<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> <span class="token function">throwHello</span><span class="token punctuation">(</span><span class="token class-name">String</span> tag<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token string">"Hello "</span> <span class="token operator">+</span> tag<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">static</span> <span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"Hello Robot"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token comment">//ReflectSample.java</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span><span class="token class-name">Field</span></span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span><span class="token class-name">InvocationTargetException</span></span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>reflect<span class="token punctuation">.</span></span><span class="token class-name">Method</span></span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ReflectSample</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ClassNotFoundException</span><span class="token punctuation">,</span> <span class="token class-name">IllegalAccessException</span><span class="token punctuation">,</span> <span class="token class-name">InstantiationException</span><span class="token punctuation">,</span> <span class="token class-name">InvocationTargetException</span><span class="token punctuation">,</span> <span class="token class-name">NoSuchMethodException</span><span class="token punctuation">,</span> <span class="token class-name">NoSuchFieldException</span> <span class="token punctuation">{</span>
        <span class="token class-name">Class</span> rc <span class="token operator">=</span> <span class="token class-name">Class</span><span class="token punctuation">.</span><span class="token function">forName</span><span class="token punctuation">(</span><span class="token string">"com.interview.javabasic.reflect.Robot"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Robot</span> r <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">Robot</span><span class="token punctuation">)</span> rc<span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"Class name is "</span> <span class="token operator">+</span> rc<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//获取方法时getDeclaredMethod()函数第二个参数是传参的类型，不能获得继承或接口的方法</span>
        <span class="token class-name">Method</span> getHello <span class="token operator">=</span> rc<span class="token punctuation">.</span><span class="token function">getDeclaredMethod</span><span class="token punctuation">(</span><span class="token string">"throwHello"</span><span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//允许访问权限</span>
        getHello<span class="token punctuation">.</span><span class="token function">setAccessible</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Object</span> str <span class="token operator">=</span> getHello<span class="token punctuation">.</span><span class="token function">invoke</span><span class="token punctuation">(</span>r<span class="token punctuation">,</span> <span class="token string">"Bob"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"getHello result is "</span> <span class="token operator">+</span> str<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//getMethod()只能获取public的方法或者是继承或接口的方法</span>
        <span class="token class-name">Method</span> sayHi <span class="token operator">=</span> rc<span class="token punctuation">.</span><span class="token function">getMethod</span><span class="token punctuation">(</span><span class="token string">"sayHi"</span><span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        sayHi<span class="token punctuation">.</span><span class="token function">invoke</span><span class="token punctuation">(</span>r<span class="token punctuation">,</span> <span class="token string">"Welcome"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//设定成员变量的值</span>
        <span class="token class-name">Field</span> name <span class="token operator">=</span> rc<span class="token punctuation">.</span><span class="token function">getDeclaredField</span><span class="token punctuation">(</span><span class="token string">"name"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//允许访问权限</span>
        name<span class="token punctuation">.</span><span class="token function">setAccessible</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        name<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>r<span class="token punctuation">,</span> <span class="token string">"Alice"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        sayHi<span class="token punctuation">.</span><span class="token function">invoke</span><span class="token punctuation">(</span>r<span class="token punctuation">,</span> <span class="token string">"Welcome"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token string">"java.ext.dirs"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token string">"java.class.path"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="GC">GC<a class="anchor" href="#GC">¶</a></h2>
<h2 id="多线程与并发">多线程与并发<a class="anchor" href="#多线程与并发">¶</a></h2>
<h3 id="进程与线程">进程与线程<a class="anchor" href="#进程与线程">¶</a></h3>
<p>进程：进程独占内存空间，保存各自运行状态，相互间不干扰且可以互相切换，为并发处理任务提供了可能。</p>
<p>线程：共享进程的内存资源，互相间切换更快捷，支持更细粒度的任务控制，使进程内的子任务的一并发执行。</p>
<p>进程是资源分配的最小单位，线程是CPU调度的最小单位。</p>
<p>所有与进程相关的资源，都被记录在PCB中。</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_PCB.png" alt="Java复习笔记_PCB.png"></p>
<p>进程是抢占处理机的调度单位。线程属于某个进程，共享其资源。</p>
<p>线程只由堆栈寄存器、程序计数器和TCB组成。</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_TCB.png" alt="Java复习笔记_TCB.png"></p>
<p>区别：</p>
<ul>
<li>线程不能看作独立应用，而进程可看作独立应用</li>
<li>进程有独立的地址空间，相互不影响，线程只是进程的不同执行路径。当线程down掉，进程也会down掉</li>
<li>线程没有独立的地址空间，多进程的程序比多线程的程序健壮</li>
<li>进程的切换比线程的切换开销大</li>
</ul>
<h3 id="Java中的进程与线程">Java中的进程与线程<a class="anchor" href="#Java中的进程与线程">¶</a></h3>
<ul>
<li>Java对OS提供的功能进行封装，包括线程与进程</li>
<li>运行一个程序会产生一个进程，进程包含至少一个线程</li>
<li>每个进程对应一个JVM实例，多个线程共享JVM里的堆，每一个线程都有自己私有的栈</li>
<li>Java采用单线程编程模型，程序会自动创建主线程</li>
<li>主线程可以创建子线程，原则上要后于子线程完成执行</li>
</ul>
<p>使用<code>Thread.currentThread()</code>获得当前的线程。</p>
<p>JVM不是只有一个线程 ，比如GC。</p>
<h3 id="线程安全的主要原因">线程安全的主要原因<a class="anchor" href="#线程安全的主要原因">¶</a></h3>
<ul>
<li>存在共享数据（临界资源）</li>
<li>存在多条线程同时操作这些共享数据</li>
</ul>
<p>解决的根本方法：</p>
<p>同一时刻有且只有一个线程在操作共享数据，其他线程必须等待该线程处理完数据后再对共享数据进行操作。</p>
<h3 id="互斥锁">互斥锁<a class="anchor" href="#互斥锁">¶</a></h3>
<p>特性：</p>
<ul>
<li>互斥性：即在同一时间只允许一个线程持有某个对象锁，通过这种特性来实现多线程的协调机制。这样在同一时间只有一个线程对需要同步的代码块（复合操作）进行访问。互斥性即原子性。</li>
<li>可见性：必须确保在锁被释放之前，对共享变量所做的修改，对于随后获得该锁的另一个线程是可见的（即在获得锁时应获得最新共享变量的值），否则另一个线程可能是在本地缓存的某个副本上继续操作，从而引起不一致。</li>
</ul>
<h3 id="synchronized">synchronized<a class="anchor" href="#synchronized">¶</a></h3>
<p>synchronzied锁的不是代码，而是对象。</p>
<p>根据获取锁的分类：获取对象锁和获取类锁。</p>
<h4 id="获取对象锁">获取对象锁<a class="anchor" href="#获取对象锁">¶</a></h4>
<p>两种方法：</p>
<ol>
<li>同步代码块（synchronized(this)，synchronized(类实例对象)），锁是小括号()中的对象</li>
<li>同步非静态方法（synchronized method），锁是当前对象的实例对象</li>
</ol>
<h4 id="获取类锁">获取类锁<a class="anchor" href="#获取类锁">¶</a></h4>
<p>两种方法：</p>
<ol>
<li>同步代码块（synchronized(类.class)），锁是小括号()中的类对象(Class对象)</li>
<li>同步静态方法（synchronzied static method），锁是当前对象的类对象(Class对象)</li>
</ol>
<h4 id="总结">总结<a class="anchor" href="#总结">¶</a></h4>
<ul>
<li>线程访问对象的同步代码块时，另外的线程可以访问该对象的非同步代码块</li>
<li>若锁住的是同一个对象，一个线程在访问对象的同步代码块时，另一个访问对象的同步代码块的线程会被阻塞</li>
<li>若锁住的是同一个对象，一个线程在访问对象的同步方法时，另一个访问对象同步方法的线程会被阻塞</li>
<li>若锁住的是同一个对象，一个线程在访问对象的同步代码块时，另一个访问对象同步方法的线程会被阻塞，反之亦然</li>
<li>同一个类的不同对象的对象锁互不干扰</li>
<li>类锁由于也是一种特殊的对象锁，因此表现和上述1,2,3,4一致，而由于一个类只有一把对象锁，所以同一个类的不同对象使用类锁，将会是同步的</li>
<li>类锁和对象锁互不干扰</li>
</ul>
<h4 id="原理">原理<a class="anchor" href="#原理">¶</a></h4>
<h5 id="重入">重入<a class="anchor" href="#重入">¶</a></h5>
<p>从互斥锁的设计上来说，当一个线程试图操作一个由其他线程持有的对象锁的临界资源时，将会进入阻塞状态。但当一个线程再次请求自己持有对象锁的临界资源的时候，这种情况就叫重入。</p>
<h5 id="Java对象头">Java对象头<a class="anchor" href="#Java对象头">¶</a></h5>
<p>对象在内存中的布局：</p>
<ul>
<li>对象头</li>
<li>实例数据</li>
<li>对齐填充</li>
</ul>
<p>对象头的结构：</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_%E5%AF%B9%E8%B1%A1%E5%A4%B4%E7%BB%93%E6%9E%84.png" alt="Java复习笔记_对象头结构.png"></p>
<p>Mark Word结构：</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_MarkWord.png" alt="Java复习笔记_MarkWord.png"></p>
<h5 id="Monitor">Monitor<a class="anchor" href="#Monitor">¶</a></h5>
<p>每个Java对象天生自带了一把看不见的锁。</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_Montior%E9%94%81.png" alt="Java复习笔记_Montior锁.png"></p>
<h4 id="synchronized的四种状态">synchronized的四种状态<a class="anchor" href="#synchronized的四种状态">¶</a></h4>
<ul>
<li>无锁</li>
<li>偏向锁</li>
<li>轻量级锁</li>
<li>重量级锁</li>
</ul>
<p>锁膨胀方向：无锁-&gt;偏向锁-&gt;轻量级锁-&gt;重量级锁</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_%E9%94%81%E6%B1%87%E6%80%BB.png" alt="Java复习笔记_锁汇总.png"></p>
<h5 id="偏向锁">偏向锁<a class="anchor" href="#偏向锁">¶</a></h5>
<p>减少同一线程获取锁的代价。</p>
<p>大多数情况下，锁不存在竞争，总是由同一线程多次获得。</p>
<p>不适用于锁竞争比较激烈的多线程场合。</p>
<p>核心思想：</p>
<p>如果一个线程呢个获得了锁，那么锁就进入偏向模式。此时Mark Word的结构也就变为偏向锁，当该线程再次请求锁，无需再做任何同步操作，即获得锁的过程只需检查Mark Word的锁标记位为偏向锁以及当前线程的ID等于ThreadID即可，这样就省去了大量有关锁申请的操作。</p>
<h5 id="轻量级锁">轻量级锁<a class="anchor" href="#轻量级锁">¶</a></h5>
<p>轻量级锁是由偏向锁升级来的，偏向锁运行一个线程进入同步块的情况下。当第二个线程加入锁争用的时候，偏向锁会升级成轻量级锁。</p>
<p>使用场景：线程交替执行同步代码块</p>
<p>若存在同一时间多个线程访问同一锁的情况，就会导致轻量级锁膨胀为重量级锁。</p>
<h6 id="加锁过程">加锁过程<a class="anchor" href="#加锁过程">¶</a></h6>
<ol>
<li>
<p>在代码进入同步代码块的时候，如果同步对象锁状态为无锁状态（锁标志位为“01”），虚拟机首先在当前线程的栈帧中创建一个名为锁记录(Lock Record)的空间，用于存储锁对象目前的Mark Word拷贝。官方称之为Displaced Mark Word。这时候线程堆栈与对象头的状态如图所示。</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/Java/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_%E5%88%9D%E5%A7%8B%E5%8C%96%E9%94%81.png" alt="Java复习笔记_初始化锁.png"></p>
</li>
<li>
<p>拷贝对象头中的Mark Word复制到锁记录中。</p>
</li>
<li>
<p>拷贝完成后，虚拟机将使用CAS操作尝试将对象的Mark Word更新为指向Lock Record的指针，并将Lock Record里的owner指针指向object mark word。如果成功，则执行步骤4,否则执行步骤5。</p>
</li>
<li>
<p>如果这个更新成功，那么这个线程就拥有了该对象的锁，并且该对象Mark Word的锁标志位设置为“00”，即表示此对象处于轻量级锁定状态，这时候线程堆栈与对象头的状态如图所示。</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/Java/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_%E8%BD%BB%E9%87%8F%E7%BA%A7%E9%94%81.png" alt="Java复习笔记_轻量级锁.png"></p>
</li>
<li>
<p>如果这个更新失败，虚拟机首先会检查对象的Mark Word是否指向当前线程的栈帧。如果是就说明当前线程已经拥有这个对象的锁，那就可以直接进入同步块继续执行。否则说明多个线程竞争锁，轻量级锁膨胀为重量级锁，锁标志位的状态值设置为“10”，Mark Word中存储的就是指向重量级锁（互斥量）的指针，后面等待锁的线程也就要进入阻塞状态。而当前线程便尝试使用自旋来获取锁。</p>
</li>
</ol>
<h3 id="锁的内存语义">锁的内存语义<a class="anchor" href="#锁的内存语义">¶</a></h3>
<p>当线程释放锁时，Java内存模型会把该线程对应的本地内存中的共享变量刷新到主内存中。</p>
<p>当线程获取锁时，Java内存模型会把该线程对应的本地内存置为无效，从而使得被监视器保护的临界区代码必须从主内存中读取共享变量。</p>
<h3 id="Thread">Thread<a class="anchor" href="#Thread">¶</a></h3>
<h4 id="run方法和start方法">run方法和start方法<a class="anchor" href="#run方法和start方法">¶</a></h4>
<p>调用run方法的时候会调用主线程执行方法，当调用start会调用非main的线程执行方法。</p>
<ul>
<li>调用start方法会创建一个新的子线程并启动</li>
<li>run方法只是Thread的一个普通的方法调用</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_run%E6%96%B9%E6%B3%95.png" alt="Java复习笔记_run方法.png"></p>
<h4 id="Runnable和Thread">Runnable和Thread<a class="anchor" href="#Runnable和Thread">¶</a></h4>
<p>Runnable只是一个接口，里面有一个抽象的run方法。</p>
<ul>
<li>Thread是实现了Runnable接口的类，使得run支持多线程</li>
<li>因类的单一继承原则，推荐多使用Runnable接口</li>
</ul>
<h4 id="变化">变化<a class="anchor" href="#变化">¶</a></h4>
<p>早期版本中，synchronzied属于重量级锁，依赖于Mutex Lock实现。线程之间的切换需要从用户态转换成核心态，开销较大。</p>
<p>JDK6之后，性能获得提升，引入Adaptive Spinning、Lock Eliminate、Lock Coarsening、Lightweight Locking、Biased Locking…</p>
<h3 id="自旋锁">自旋锁<a class="anchor" href="#自旋锁">¶</a></h3>
<ul>
<li>许多情况下，共享数据的锁定状态持续时间较短，切换进程不值得</li>
<li>通过让线程执行忙循环等待锁的释放，不让出CPU</li>
<li>缺点：若锁被其他线程长时间占用，会带来许多性能上的开销</li>
</ul>
<p>可以使用PerBlockSpin进行更改。</p>
<h3 id="自适应自旋锁">自适应自旋锁<a class="anchor" href="#自适应自旋锁">¶</a></h3>
<ul>
<li>自旋的次数不再固定</li>
<li>由前一次在同一个锁上的自旋时间及锁的拥有这的状态来决定</li>
</ul>
<h3 id="锁消除">锁消除<a class="anchor" href="#锁消除">¶</a></h3>
<p>JIT编译时，对运行上下文进行扫描，去除不可能存在竞争的锁。</p>
<h3 id="锁粗化">锁粗化<a class="anchor" href="#锁粗化">¶</a></h3>
<p>为了帮助一连串琐碎的加锁去锁的过程，在外部加锁。</p>
<h3 id="run方法传参">run方法传参<a class="anchor" href="#run方法传参">¶</a></h3>
<ul>
<li>构造函数传参</li>
<li>成员变量传参</li>
<li>回调函数传参</li>
</ul>
<h3 id="处理线程的返回值">处理线程的返回值<a class="anchor" href="#处理线程的返回值">¶</a></h3>
<ul>
<li>主线程等待法，需要自己实现等待的方法。当变量多的时候，会导致代码繁琐，无法做到精准的控制</li>
<li>使用Thread类的join方法阻塞当前进程以等待子线程处理完毕。但是粒度粗。</li>
<li>通过Callable接口实现：通过FutureTask Or 线程池获取</li>
</ul>
<h4 id="Callable接口">Callable接口<a class="anchor" href="#Callable接口">¶</a></h4>
<p>该接口中只有一个抽象方法：call()。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//MyCallable.java</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span><span class="token class-name">Callable</span></span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyCallable</span> <span class="token keyword">implements</span> <span class="token class-name">Callable</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">call</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span><span class="token punctuation">{</span>
        <span class="token class-name">String</span> value<span class="token operator">=</span><span class="token string">"test"</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"Ready to work"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"task done"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span>  value<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token comment">//FutureTaskDemo.java</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span><span class="token class-name">ExecutionException</span></span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span><span class="token class-name">FutureTask</span></span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">FutureTaskDemo</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ExecutionException</span><span class="token punctuation">,</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">{</span>
        <span class="token class-name">FutureTask</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> task <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FutureTask</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">MyCallable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span>task<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token operator">!</span>task<span class="token punctuation">.</span><span class="token function">isDone</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"task has not finished, please wait!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"task return: "</span> <span class="token operator">+</span> task<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>FutureTask的isDone方法表示线程执行完成，get方法获取返回值，get方法能设定最长等待时间，直接传参即可。</p>
<h4 id="线程池">线程池<a class="anchor" href="#线程池">¶</a></h4>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//MyCallable.java</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span><span class="token class-name">Callable</span></span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyCallable</span> <span class="token keyword">implements</span> <span class="token class-name">Callable</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">call</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span><span class="token punctuation">{</span>
        <span class="token class-name">String</span> value<span class="token operator">=</span><span class="token string">"test"</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"Ready to work"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"task done"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span>  value<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token comment">//ThreadPoolDemo.java</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span><span class="token class-name">ExecutionException</span></span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span><span class="token class-name">ExecutorService</span></span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span><span class="token class-name">Executors</span></span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token import"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span><span class="token class-name">Future</span></span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ThreadPoolDemo</span> <span class="token punctuation">{</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">ExecutorService</span> newCachedThreadPool <span class="token operator">=</span> <span class="token class-name">Executors</span><span class="token punctuation">.</span><span class="token function">newCachedThreadPool</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Future</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> future <span class="token operator">=</span> newCachedThreadPool<span class="token punctuation">.</span><span class="token function">submit</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">MyCallable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token operator">!</span>future<span class="token punctuation">.</span><span class="token function">isDone</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"task has not finished, please wait!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>future<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ExecutionException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
            newCachedThreadPool<span class="token punctuation">.</span><span class="token function">shutdown</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>通过<code>Executors.newCachedThreadPool</code>创建<code>ExecutorService</code>对象。通过对象的submit方法包裹继承Callable接口的自定义类，注意这里的返回值使用Future去接收。最后记得关闭线程池，使用ExecutorService的shutdown方法。</p>
<h3 id="线程的状态">线程的状态<a class="anchor" href="#线程的状态">¶</a></h3>
<p>六个状态：</p>
<ul>
<li>
<p>新建（New）：创建后尚未启动的状态</p>
</li>
<li>
<p>运行（Runnable）：包含Running和Ready</p>
</li>
<li>
<p>无限期等待（Waiting）：不会被分配CPU执行时间，需要显式被唤醒。</p>
<ul>
<li>没有设置Timeout参数的Object.wait()方法</li>
<li>没有设置Timeout参数的Thread.join()方法</li>
<li>LockSupport.park()方法</li>
</ul>
</li>
<li>
<p>限期等待（Timed Waiting）：在一定时间后由系统自动唤醒</p>
<ul>
<li>Thread.sleep()方法</li>
<li>设置Timeout参数的Object.wait()方法</li>
<li>设置Timeout参数的Thread.join()方法</li>
<li>LockSupport.parkNanos()方法</li>
<li>LockSupport.parkUtil()方法</li>
</ul>
</li>
<li>
<p>阻塞（Blocked）：等待获取排它锁</p>
</li>
<li>
<p>结束（Terminated）：已终止线程的状态，线程已经结束执行</p>
</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_%E7%BA%BF%E7%A8%8B%E7%8A%B6%E6%80%81%E5%9B%BE.png" alt="Java复习笔记_线程状态图.png"></p>
<h3 id="sleep和wait">sleep和wait<a class="anchor" href="#sleep和wait">¶</a></h3>
<ul>
<li>sleep()是Thread类的方法，wait是Object类中定义的方法</li>
<li>sleep()方法可以在任何地方使用</li>
<li>wait()方法只能在synchronized方法或synchronized块中使用</li>
<li><strong>Thread.sleep()只会让出CPU,不会导致锁行为的改变</strong></li>
<li><strong>Object.wait()不仅让出CPU,还会释放已经占用的同步资源锁</strong></li>
<li>Object.wait()方法能被notify和notifyAll唤醒</li>
</ul>
<h3 id="notify和notifyAll">notify和notifyAll<a class="anchor" href="#notify和notifyAll">¶</a></h3>
<h4 id="锁池EntryList">锁池EntryList<a class="anchor" href="#锁池EntryList">¶</a></h4>
<p>假设线程A已经拥有了某个对象（不是类）的锁，而其他线程B、C想要调用这个对象的某个synchronized方法（或者块），由于B、C线程在进入对象的synchronized方法（或者块）之前必须获得该对象锁的拥有权，而恰好该对象的锁目前正被线程A所占用。此时B、C线程就会被阻塞，进入一个地方等待锁的释放，这个地方就是该对象的锁池。</p>
<h4 id="等待池WaitSet">等待池WaitSet<a class="anchor" href="#等待池WaitSet">¶</a></h4>
<p>假设线程A调用了某个对象的wait()方法，线程A就会释放该对象的锁。同时线程A就进入到该对象的等待池中，不会去竞争该对象的锁。</p>
<h4 id="区别">区别<a class="anchor" href="#区别">¶</a></h4>
<ul>
<li>notifyAll会让所有处于等待池的线程全部进入锁池去竞争获取锁的机会</li>
<li>notify只会随即选取一个处于等待池中的线程进入锁池去争取竞争获取锁的机会</li>
</ul>
<h3 id="yield">yield<a class="anchor" href="#yield">¶</a></h3>
<p>当调用Thread.yield()函数时，会给线程调度器一个当前线程愿意让出CPU使用的暗示，但是线程调度器可能会忽略这个暗示。<strong>但是不会释放锁资源。</strong></p>
<h3 id="中断线程">中断线程<a class="anchor" href="#中断线程">¶</a></h3>
<p>已经被抛弃的方法：</p>
<ul>
<li>通过调用stop()停止线程</li>
<li>通过调用suspend()方法和resume()方法</li>
</ul>
<p>目前使用的方法：</p>
<p>调用interrupt()方法，通知线程应该中断了。</p>
<ul>
<li>如果线程处于被阻塞的状态，那么线程将立即推出被阻塞的状态，并抛出一个InterruptedException异常</li>
<li>如果线程处于正常活动状态，那么会将该线程的中断标志设置为true.被设置中断标志的线程将继续正常运行，不受影响</li>
</ul>
<h2 id="常见类库">常见类库<a class="anchor" href="#常见类库">¶</a></h2>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_%E9%9B%86%E5%90%88%E6%A1%86%E6%9E%B6.png" alt="Java复习笔记_集合框架.png"></p>
<h3 id="List和Set">List和Set<a class="anchor" href="#List和Set">¶</a></h3>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_List&amp;Set.png" alt="Java复习笔记_List&amp;Set.png"></p>
<h3 id="Map">Map<a class="anchor" href="#Map">¶</a></h3>
<h4 id="HashMap">HashMap<a class="anchor" href="#HashMap">¶</a></h4>
<p><strong>在HashMap中，null可以作为键，这样的键只有一个；可以有一个或多个键所对应的值为null。</strong></p>
<p>当get()方法返回null值时，即可以表示 HashMap中没有该键，也可以表示该键所对应的值为null。因此，在HashMap中不能由get()方法来判断HashMap中是否存在某个键， 而应该用containsKey()方法来判断。</p>
<p>在Java8以前实现方式为数组+链表。</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_HashMap.png" alt="Java复习笔记_HashMap.png"></p>
<p>当大量数值的hash值相同时，则存储在链表中。链表查找是通过便利进行查找，所以性能恶化时，会从<img src="https://math.now.sh?inline=O%281%29" style="filter: opacity(95%);transform:scale(0.85);text-align:center;display:inline-block;margin: 0;">变成<img src="https://math.now.sh?inline=O%28n%29" style="filter: opacity(95%);transform:scale(0.85);text-align:center;display:inline-block;margin: 0;">。</p>
<p>在Java8之后实现方式变为数组+链表+红黑树。</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_HashMap_JDK8.png" alt="Java复习笔记_HashMap_JDK8"></p>
<p>当链表超过8时，链表变化成红黑树。当链表小于6时，退化成链表。</p>
<p>put方法的逻辑：</p>
<ol>
<li>如果HashMap未被初始化过，则初始化</li>
<li>对Key求Hash值，然后再计算下标</li>
<li>如果没有碰撞，直接放入桶中</li>
<li>如果碰撞，以链表的方式链接到后面</li>
<li>如果链表长度超过阈值，就把链表转成红黑树</li>
<li>如果链表长度低于6,就把红黑树转回成链表</li>
<li>如果节点已经存在就替换旧值</li>
<li>如果桶满了（容量16×加载因子0.75），就需要resize（扩容后重排）</li>
</ol>
<p>默认的负载因子大小为0.75，也就是说，当一个map填满了75%的bucket时候，和其它集合类(如ArrayList等)一样，将会创建原来HashMap大小的两倍的bucket数组，来重新调整map的大小，并将原来的对象放入新的bucket数组中。这个过程叫作rehashing，因为它调用hash方法找到新的bucket位置。</p>
<p>如何有效的减少碰撞：</p>
<ul>
<li>扰动函数：促使元素位置分布均匀，减少碰撞几率</li>
<li>使用final对象，并采用合适的equals和hashCode方法</li>
</ul>
<p>重新调整HashMap大小存在的问题：</p>
<p>当重新调整HashMap大小的时候，确实存在条件竞争，因为如果两个线程都发现HashMap需要重新调整大小了，它们会同时试着调整大小。在调整大小的过程中，存储在链表中的元素的次序会反过来，因为移动到新的bucket位置的时候，HashMap并不会将元素放在链表的尾部，而是放在头部，这是为了避免尾部遍历(tail traversing)。如果条件竞争发生了，那么就死循环了。</p>
<p>获取hash到散列的过程：</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_HashMapGetHash.png" alt="Java复习笔记_HashMapGetHash.png"></p>
<p>HashMap 底层数组的长度总是 2 的 n 次方。</p>
<p>当 length 总是 2 的倍数时，h &amp; (length-1) 将是一个非常巧妙的设计：假设 h=5,length=16, 那么 h &amp; length - 1 将得到 5；如果 h=6,length=16, 那么 h &amp; length - 1 将得到 6 ……如果 h=15,length=16, 那么 h &amp; length - 1 将得到 15；但是当 h=16 时 , length=16 时，那么 h &amp; length - 1 将得到 0 了；当 h=17 时 , length=16 时，那么 h &amp; length - 1 将得到 1 了……这样保证计算得到的索引值总是位于 table 数组的索引之内。</p>
<p><strong>增大负载因子可以减少 Hash 表（就是那个 Entry 数组）所占用的内存空间，但会增加查询数据的时间开销，而查询是最频繁的的操作（HashMap 的 get() 与 put() 方法都要用到查询）；减小负载因子会提高数据查询的性能，但会增加 Hash 表所占用的内存空间。</strong></p>
<p>扩容问题：</p>
<ul>
<li>多线程环境下，调整大小会存在条件竞争，容易造成死锁</li>
<li>rehashing是一个比较耗时的过程</li>
</ul>
<p>HashMap变成线程安全需要用<code>Collections.synchronizedMap()</code>包裹。因为synchronizedMap里面有一个final属性的mutex进行控制。</p>
<h4 id="HashTable">HashTable<a class="anchor" href="#HashTable">¶</a></h4>
<p>HashTable是线程安全的，所有方法都被<code>synchronized</code>修饰。因为是串行执行，所以效率较低。</p>
<p>可以通过锁细粒度化，将整把锁拆分成多个锁进行优化。</p>
<p><strong>Hashtable中，key和value都不允许出现null值。</strong></p>
<h4 id="ConccurentHashMap">ConccurentHashMap<a class="anchor" href="#ConccurentHashMap">¶</a></h4>
<p>早期ConcurrentHashMap：通过分化锁Segment实现。</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_%E6%97%A9%E6%9C%9FConcurrentHashMap.png" alt="Java复习笔记_早期ConcurrentHashMap.png"></p>
<p>当前的ConcurrentHashMap：CAS+synchronized使得锁更细化。</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_ConcurrentHashMap.png" alt="Java复习笔记_ConcurrentHashMap.png"></p>
<h3 id="HashSet">HashSet<a class="anchor" href="#HashSet">¶</a></h3>
<p>HashSet 本身就采用 HashMap 来实现的。但是HashMap是Map接口的常用实现类，HashSet是Set接口的常用实现类。接口规范不同，但是底层的Hash存储机制完全一样。</p>
<p>HashSet的实现其实非常简单，它只是封装了一个HashMap对象来存储所有的集合元素。所有放入HashSet中的集合元素实际上由HashMap的key来保存，而HashMap的value则存储了一个PRESENT，它是一个静态的Object对象。</p>
<h3 id="String、StringBuffer、StringBuilder">String、StringBuffer、StringBuilder<a class="anchor" href="#String、StringBuffer、StringBuilder">¶</a></h3>
<p>String是字符串常量，而StringBuffer和StringBuilder是字符串变量。由String创建的字符内容是不可改变的，而由StringBuffer和StringBuilder创建的字符内容是可以改变的。</p>
<p>StringBuffer是线程安全的，而StringBuilder是非线程安全的。StringBuilder是从JDK 5开始，为StringBuffer类补充的一个单线程的等价类。<strong>我们在单线程使用时应优先考虑使用StringBuilder</strong>，因为它支持StringBuffer的所有操作，但是因为它不执行同步，不会有线程安全带来额外的系统消耗，所以速度更快。</p>
<p>虽然String、StringBuffer和StringBuilder都是final类，它们生成的对象都是不可变的，而且它们内部也都是靠char数组实现的，但是不同之处在于，String类中定义的char数组是final的，而StringBuffer和StringBuilder都是继承自AbstractStringBuilder类，它们的内部实现都是靠这个父类完成的，而这个父类中定义的char数组只是一个普通是私有变量，可以用append追加。因为AbstractStringBuilder实现了Appendable接口。</p>
<h2 id="异常">异常<a class="anchor" href="#异常">¶</a></h2>
<ul>
<li>What：异常类型回答了什么被抛出</li>
<li>Where：异常堆栈跟踪回答了在哪被抛出</li>
<li>Why：异常信息回答了为什么被抛出</li>
</ul>
<p><strong>try-catch块影响JVM优化，并且异常对象实例需要保存栈快照等信息，开销较大。</strong></p>
<h3 id="Error和Exception">Error和Exception<a class="anchor" href="#Error和Exception">¶</a></h3>
<ul>
<li>Error：程序无法处理的系统错误，编译器不做检查</li>
<li>Exception：程序可以处理的异常，捕获后可能恢复</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_%E5%BC%82%E5%B8%B8.png" alt="Java复习笔记_异常.png"></p>
<ul>
<li>RuntimeException：不可预知，程序应当自行避免</li>
<li>非RuntimeException：可预知，从编译器校验的异常</li>
</ul>
<h3 id="常见的Error和Exception">常见的Error和Exception<a class="anchor" href="#常见的Error和Exception">¶</a></h3>
<h4 id="RuntimeException">RuntimeException<a class="anchor" href="#RuntimeException">¶</a></h4>
<ul>
<li>NullPointerException——空指针引用异常</li>
<li>ClassCastException——类型强制转换异常</li>
<li>IllegalArgumentException——传递非法参数异常</li>
<li>IndexOutOfBoundsException——下标越界异常</li>
<li>NumberFormatException——数字格式异常</li>
</ul>
<h4 id="非RuntimeException">非RuntimeException<a class="anchor" href="#非RuntimeException">¶</a></h4>
<ul>
<li>ClassNotFoundException——找不到指定的class的异常</li>
<li>IOException——IO操作异常</li>
</ul>
<h4 id="Error">Error<a class="anchor" href="#Error">¶</a></h4>
<ul>
<li>NoClassDefFoundError——找不到class定义异常</li>
<li>StackOverflowError——深递归导致栈被耗尽而抛出的异常</li>
<li>OutofMemoryError——内存溢出异常</li>
</ul>
<h3 id="异常处理机制">异常处理机制<a class="anchor" href="#异常处理机制">¶</a></h3>
<ul>
<li>抛出异常：创建异常对象，交由运行时系统处理</li>
<li>捕获异常：寻找合适的异常处理器处理异常，否则终止执行</li>
</ul>
<h2 id="Spring">Spring<a class="anchor" href="#Spring">¶</a></h2>
<h3 id="依赖注入">依赖注入<a class="anchor" href="#依赖注入">¶</a></h3>
<p>把底层类作为参数传递给上层类，实现上层对下层的“控制”。</p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_Spring_DI.png" alt="Java复习笔记_Spring_DI.png"></p>
<h3 id="IOC">IOC<a class="anchor" href="#IOC">¶</a></h3>
<p>IOC支持的功能：</p>
<ul>
<li>依赖注入</li>
<li>依赖检查</li>
<li>自动装配</li>
<li>支持集合</li>
<li>指定初始化方法和销毁方法</li>
<li>支持回调方法</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_Spring_IOC.png" alt="Java复习笔记_Spring_IOC.png"></p>
<p>IOC容器的优势：</p>
<ul>
<li>避免在各处使用new来创建类，并且可以做到统一维护。</li>
<li>创建实例的时候不需要了解其中的细节。</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_Spring_IOC%E6%B5%81%E7%A8%8B.png" alt="Java复习笔记_Spring_IOC流程.png"></p>
<h4 id="IOC容器的核心接口">IOC容器的核心接口<a class="anchor" href="#IOC容器的核心接口">¶</a></h4>
<h5 id="BeanFactory">BeanFactory<a class="anchor" href="#BeanFactory">¶</a></h5>
<p>Spring框架最核心的接口。</p>
<ul>
<li>提供了IOC的配置机制。</li>
<li>包含Bean的各种定义，便于实例化Bean。</li>
<li>建立Bean之间的依赖关系。</li>
<li>Bean生命周期的控制。</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_BeanFactory%E4%BD%93%E7%B3%BB.png" alt="Java复习笔记_BeanFactory体系.png"></p>
<h5 id="ApplicationContext">ApplicationContext<a class="anchor" href="#ApplicationContext">¶</a></h5>
<p>ApplicationContext是BeanFactory的子接口之一。</p>
<p>ApplicationContext的功能（继承多个接口）</p>
<ul>
<li>BeanFactory：能够管理、装配Bean。</li>
<li>ResourcePatternResolver：能够加载资源文件。</li>
<li>MessageSource：能够实现国际化等功能。</li>
<li>ApplicationEventPublisher：能够注册监听器，实现监听机制。</li>
</ul>
<h5 id="比较">比较<a class="anchor" href="#比较">¶</a></h5>
<ul>
<li>Beanfactory是Spring框架的基础设施，面向Spring。</li>
<li>ApplicationContext面向使用Spring框架的开发者。</li>
</ul>
<p>BeanDefinition：主要用来描述Bean定义。</p>
<p>BeanDefinitionRegistry：提供向IOC容器注册BeanDefinition对象的方法。</p>
<h3 id="Bean的作用域">Bean的作用域<a class="anchor" href="#Bean的作用域">¶</a></h3>
<ul>
<li>singleton：Spring的默认作用域，容器里拥有唯一的Bean实例。适合无状态Bean。</li>
<li>prototype：针对每个getBean请求，容器都会创建一个Bean实例。适合有状态的Bean。</li>
<li>request：会为每个HTTP请求创建一个Bean实例。</li>
<li>session：会为每个session创建一个Bean实例。</li>
<li>golbalSession：会为每个全局HTTP Session创建一个Bean,该最用于仅对Portlet有效。</li>
</ul>
<h3 id="Bean的生命周期">Bean的生命周期<a class="anchor" href="#Bean的生命周期">¶</a></h3>
<h6 id="创建过程">创建过程<a class="anchor" href="#创建过程">¶</a></h6>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Java/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0/Java%E5%A4%8D%E4%B9%A0%E7%AC%94%E8%AE%B0_Bean%E5%88%9B%E5%BB%BA%E6%B5%81%E7%A8%8B.png" alt="Java复习笔记_Bean创建流程.png"></p>
<h6 id="销毁过程">销毁过程<a class="anchor" href="#销毁过程">¶</a></h6>
<ul>
<li>若实现了DisposableBean接口，则会调用destory方法。</li>
<li>若配置了destory-method属性，则会调用其配置的销毁方法。</li>
</ul>
<h3 id="AOP">AOP<a class="anchor" href="#AOP">¶</a></h3>
<p>关注点分离：不同的问题交给不同的部分去解决。</p>
<ul>
<li>面向切面编程AOP正是此种技术的实现</li>
<li>通用化功能代码的实现，对应的就是所谓的切面（Aspect）</li>
<li>业务功能代码和切面代码分开后，架构将变得高内聚低耦合</li>
<li>确保功能的完整性：切面最终需要被合并到业务中（Weave）</li>
</ul>
<h4 id="三种织入方式">三种织入方式<a class="anchor" href="#三种织入方式">¶</a></h4>
<ul>
<li>编译时织入：需要特殊的Java编译器，如AspectJ</li>
<li>类加载时织入：需要特殊的Java编译器，如AspectJ和AspectWerkz</li>
<li>运行时织入：Spring采用的方式，通过动态代理的方式，实现简单</li>
</ul>
<h4 id="主要名词概念">主要名词概念<a class="anchor" href="#主要名词概念">¶</a></h4>
<ul>
<li>Aspect：通用功能的代码实现</li>
<li>Target：被织入Aspect的对象</li>
<li>Join point：可以作为切入点的机会，所有方法都可以作为切入点</li>
<li>Pointcut：Aspect世纪被应用在的Join Point,支持正则</li>
<li>Advice：类里的方法以及这个方法如何织入到目标方法的方式</li>
<li>Waving：AOP的实现过程</li>
</ul>
<h4 id="Advice的种类">Advice的种类<a class="anchor" href="#Advice的种类">¶</a></h4>
<ul>
<li>前置通知（Before）</li>
<li>后置通知（AfterReturning）</li>
<li>异常通知（AfterThrowing）</li>
<li>最终通知（After）</li>
<li>环绕通知（Around）</li>
</ul>
<h4 id="AOP的实现">AOP的实现<a class="anchor" href="#AOP的实现">¶</a></h4>
<p>AOP的实现通过JdkProxy和Cglib。</p>
<ul>
<li>由AopProxyFactory根据AdvisedSupport对象的配置来决定</li>
<li>默认策略如果目标类是接口，则用JDKProxy实现，否则后者</li>
<li>JDKProxy的核心：InvocationHandler接口类和Proxy类</li>
<li>Cglib：以继承的方式动态生成目标类的代理</li>
<li>JDKProxy：通过Java的内部反射机制实现，反射机制在生成类的过程中比较高效</li>
<li>Cglib：借助ASM实现，ASM是一种能够操作字节码的框架，ASM在生成类之后的执行过程中比较高效，可以使用缓存的方式，改善ASM生成类过程中缓慢的问题</li>
</ul>
<h3 id="ACID">ACID<a class="anchor" href="#ACID">¶</a></h3>
<h3 id="隔离级别">隔离级别<a class="anchor" href="#隔离级别">¶</a></h3>
<h3 id="事务传播">事务传播<a class="anchor" href="#事务传播">¶</a></h3>
<h2 id="Tip">Tip<a class="anchor" href="#Tip">¶</a></h2>
<h3 id="static、final、static-final的区别">static、final、static final的区别<a class="anchor" href="#static、final、static-final的区别">¶</a></h3>
<h4 id="final">final<a class="anchor" href="#final">¶</a></h4>
<p>可以修饰属性、方法、类、局部变量。</p>
<p>初始化可以在编译期或者运行期，<strong>初始化后不能改变。</strong></p>
<p>与具体对象有关，在运行期初始化的final属性，不同对象可以有不同值。</p>
<p>final类无法被继承，没有子类，final类中的方法默认是final的。</p>
<p>final方法不能被子类的方法覆盖，但是可以被继承。</p>
<p><strong>final成员变量表示常量，只能被赋值一次。其后不能改变。</strong></p>
<p>不能用于修饰构造方法。</p>
<p>private类型的方法默认是final类型的。</p>
<ul>
<li>对于基本数据类型：是常量，创建后不能修改。</li>
<li>对于对象句柄：final将句柄变成常数（在声明时，必须将句柄初始化到一个具体的对象，而且不能再将句柄指向另一个对象。<strong>但是对象本身是可以修改的</strong>）</li>
<li>对于数组：数组属于对象，数组本身也可以改。同对象。</li>
<li>对于方法参数中的final句柄：在该方法内部不能改变参数句柄指向的实际东西，不能给形参句柄再赋值。</li>
</ul>
<h4 id="static">static<a class="anchor" href="#static">¶</a></h4>
<p>可以修饰属性、方法、代码段、内部类（静态或嵌套内部类）</p>
<p>初始化在编译期，初始化后能改变。</p>
<p>static与具体对象无关。</p>
<p>不可以修饰局部变量。</p>
<p>**被static修饰的成员变量和成员方法独立于该类的任何对象。**被所有类的实例共享。只要这个类被加载，Java虚拟机就能根据类名在运行时数据区的方法区内找到它们。可以在任意对象创建之前访问，无需引用任何对象。</p>
<h4 id="final-static">final static<a class="anchor" href="#final-static">¶</a></h4>
<p><strong>static修饰的属性强调它们只有一个，final修饰的属性强调是一个常数</strong>。</p>
<h3 id="不同JDK版本之间的intern-方法的区别">不同JDK版本之间的intern()方法的区别<a class="anchor" href="#不同JDK版本之间的intern-方法的区别">¶</a></h3>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">String</span> s <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
s<span class="token punctuation">.</span><span class="token function">intern</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>JDK6：当调用intern方法时，如果字符串常量池先前已创建出该字符串对象，则返回池中的该字符串的引用。否则，将此字符串对象添加到字符串常量池中，并且返回该字符串对象的引用。</p>
<p>JDK6+：当调用intern方式时，如果字符串常量池先前已创建出该字符串对象，则返回池中的该字符串的引用。否则，如果该字符串对象已经存在于Java堆中，则将堆中对此对象的引用添加到字符串常量池中，并且返回该引用。如果堆中不存在，则在池中创建该字符串并返回其引用。</p>
<h3 id="getBean方法的代码逻辑">getBean方法的代码逻辑<a class="anchor" href="#getBean方法的代码逻辑">¶</a></h3>
<ol>
<li>转换beanName</li>
<li>从缓存中加载实例</li>
<li>实例化Bean</li>
<li>检测parentBeanFactory</li>
<li>初始化依赖的Bean</li>
<li>创建Bean</li>
</ol>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">不二</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://buerlog.top/2020/10/28/cheng-xu-she-ji/java/java-fu-xi-bi-ji/">http://buerlog.top/2020/10/28/cheng-xu-she-ji/java/java-fu-xi-bi-ji/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">不二</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Java/">
                                    <span class="chip bg-color">Java</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2020/11/10/suan-fa/leetcode-he-ji/leetcode-shua-ti-ji-lu/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/PageImg/算法/leetcode.png" class="responsive-img" alt="Leetcode刷题记录">
                        
                        <span class="card-title">Leetcode刷题记录</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-11-10
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%AE%97%E6%B3%95/" class="post-category">
                                    算法
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Cpp/">
                        <span class="chip bg-color">Cpp</span>
                    </a>
                    
                    <a href="/tags/Leetcode/">
                        <span class="chip bg-color">Leetcode</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/09/29/cheng-xu-she-ji/java/java-jia-gou-zhi-lu-dan-ti/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/PageImg/程序设计/architecture.png" class="responsive-img" alt="Java架构之旅--单体">
                        
                        <span class="card-title">Java架构之旅--单体</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-09-29
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/" class="post-category">
                                    程序设计
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Java/">
                        <span class="chip bg-color">Java</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 不二博客<br />'
            + '文章作者: 不二<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="song"
                   id="1901371647"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2018-2023</span>
            
            <span id="year">2018</span>
            <a href="/about" target="_blank">不二</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">263.4k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2018";
                    var startMonth = "5";
                    var startDate = "25";
                    var startHour = "17";
                    var startMinute = "20";
                    var startSecond = "53";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/weiyouwozuiku" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:weiyouwozuiku@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1104891151" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1104891151" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/he-he-9-35-47" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/he-he-9-35-47" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>

    <script src='https://unpkg.com/mermaid@8.14.0/dist/mermaid.min.js'></script>
    <script>
      if (window.mermaid) {
        mermaid.initialize({theme: 'forest'});
      }
    </script>
  

    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/materialize/materialize.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/aos/aos.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/js/matery.js"></script>

    <!-- Baidu Analytics -->

<script>
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?943a68f473d421f2d98228f74edc63d0";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    
    <script async src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="150"
        src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
